import {
  combineLatest,
  concat,
  forkJoin,
  from,
  fromEvent,
  interval,
  map,
  merge,
  of,
  partition,
  race,
  take,
  timer,
  zip,
} from "rxjs";

export function partitionDemo() {
  const ofObs = of(1, 2, 3, 4, 5, 6, 7, 8);
  // 通过partition 构建出来个Obaserable 对象，一个是满足条件的，一个是不满足条件的；
  const [isTrue$, isFalse$] = partition(ofObs, (x) => x % 2 === 0);

  isTrue$.subscribe((x) => console.log(x, '满足条件的'));
  // 不满足条件
  isFalse$.subscribe((x) => console.log(x, '不满足条件的'));
}

export function zipDemo() {
  // 主要是把多个observable 压缩成一个Obaseable, 在处理加压缩后的obserable
  const zipObs = zip(
    from([1, 2, 3]),
    of("zhgnsan", "lisi", "wangwu"),
    of(true, false, true),
  );

  zipObs
    .pipe(
      map(([age, userName, isDev]) => {
        return {
          age,
          userName,
          isDev,
        };
      }),
    )
    .subscribe((x) => {
      console.log(x);
    });
}

export function raceDemo() {
  // race 是就是找最快的, 类型Promise.race
  race(
    interval(5000).pipe(map(() => "first")),
    interval(2000).pipe(map(() => "second")),
    interval(8000).pipe(map(() => "three")),
  ).subscribe((x) => {
    console.log(x);
  });
}

export function mergeDemo() {
  const clicks$ = fromEvent(document, "click");
  const timer$ = interval(1000);

  // 把两个 obserable 合并到一块，执行顺序是该谁执行谁执行！
  const merObs = merge(clicks$, timer$);

  merObs.subscribe((x) => {
    console.log(x);
  });
}

export function forkJoinDemo() {
  const ofObs = of(1, 2, 3, 4);
  const promiseObs = new Promise((resolve) => {
    setTimeout(() => {
      resolve(90);
    }, 8000);
  });
  const timerObs = timer(4000);

  console.time("label");

  // 这可以把多个 obserable 或者primse整合到一块；在一个订阅事件中统一执行;
  forkJoin({
    of: ofObs,
    promisObs: promiseObs,
    timer: timerObs,
  }).subscribe((x) => {
    console.log(x);
    console.timeEnd("label");
  });
}

export function concatDemo() {
  const timer1 = interval(1000).pipe(take(4));
  const timer2 = interval(2000).pipe(take(6));

  const timer3 = interval(200).pipe(take(3));

  // 会把上面的 timer1,timer2, timer3, 按顺序执行；
  const concatTimer = concat(timer1, timer2, timer3);

  concatTimer.subscribe((x) => {
    // 在这里面会执行 timer1, timer2, timer3 的顺序执行；
    console.log(x);
  });
}

export function combineLastestDemo2() {
  const weight = of(70, 72, 76, 79, 75);
  const height = of(1.76, 1.77, 1.78);

  const bim = combineLatest([weight, height]);

  bim.subscribe((x) => {
    console.log(x);
  });

  /**
   * [70, 1.76]
[72, 1.76]
[76, 1.76]
[79, 1.76]
[75, 1.76]
[70, 1.77]
[72, 1.77]
[76, 1.77]
[79, 1.77]
[75, 1.77]
[70, 1.78]
[72, 1.78]
[76, 1.78]
[79, 1.78]
[75, 1.78]
  */
}

export function combineLastestDemo() {
  console.log("hhhh");

  const firstTime = timer(0, 1000);
  const secondTimer = timer(500, 1000);

  const combinObs = combineLatest([firstTime, secondTimer]);

  combinObs.subscribe((x) => {
    console.log(x);
  });
}
